咒語:使用mui組件建立一個音樂撥放器 並且包含上傳按鈕 用上傳的不要路徑 播放邏輯(再按一次可暫停)/音樂進度條/音量進度條 內容以繁體中文表示 不使用react-audio-player
import React, { useState, useRef } from "react";
import {
Box,
Button,
Container,
Slider,
Typography,
} from "@mui/material";
const MusicPlayer = () => {
const [isPlaying, setIsPlaying] = useState(false);
const [volume, setVolume] = useState(0.5);
const audioRef = useRef(null);
const togglePlay = () => {
if (isPlaying) {
audioRef.current.pause();
} else {
audioRef.current.play();
}
setIsPlaying(!isPlaying);
};
const handleVolumeChange = (event, newValue) => {
setVolume(newValue);
audioRef.current.volume = newValue;
};
const handleFileChange = (event) => {
const file = event.target.files[0];
if (file) {
const objectURL = URL.createObjectURL(file);
audioRef.current.src = objectURL;
audioRef.current.play();
setIsPlaying(true);
}
};
return (
<Container>
<Box my={4}>
<audio ref={audioRef} src="" controls></audio>
</Box>
<Box display="flex" alignItems="center">
<Button
variant="contained"
color={isPlaying ? "secondary" : "primary"}
onClick={togglePlay}
>
{isPlaying ? "暂停" : "播放"}
</Button>
<input
type="file"
accept="audio/*"
onChange={handleFileChange}
style={{ display: "none" }}
id="audio-file"
/>
<label htmlFor="audio-file">
<Button variant="contained" component="span">
上载音乐
</Button>
</label>
</Box>
<Box my={4}>
<Typography id="volume-slider" gutterBottom>
音量
</Typography>
<Slider
value={volume}
onChange={handleVolumeChange}
aria-labelledby="volume-slider"
min={0}
max={1}
step={0.01}
/>
</Box>
</Container>
);
};
export default MusicPlayer;
這次mui的功能用的比較少 居然靠html5 audio就完成部份了
只能查看邏輯跟音量動態